package com.jxj.study.util;

import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.net.ssl.HttpsURLConnection;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class WatermarkUtil {
    public static void markeWatermark(File file, String waterMarkContent, OutputStream outputStream) throws Exception {
        if (file == null
                || !file.isFile()
                || !file.exists()
                || !file.canRead()
                || StringUtils.isBlank(waterMarkContent)) {
            throw new Exception("文件无效");
        }
        // 加水印
        BufferedImage bufImg = ImageIO.read(file);
        int imgWidth = bufImg.getWidth(null);
        int imgHeight = bufImg.getHeight(null);
        Graphics2D g = bufImg.createGraphics();
        g.drawImage(bufImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
        g.rotate(Math.toRadians(330), (double) bufImg.getWidth() / 2, (double) bufImg.getHeight() / 2);
        //根据图片的背景设置水印颜色
        g.setColor(Color.red);
        //设置字体
        g.setFont(new Font("宋体", Font.PLAIN, 20));
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                0.5f));
        for (int x = 50; x < imgHeight; x += 100) {
            for (int y = 75; y < imgWidth; y += 150) {
                //画出水印
                g.drawString(waterMarkContent, x, y);
            }
        }
        ImageIO.write(bufImg, "png", outputStream);
        outputStream.flush();
        outputStream.close();
    }

    private static final List<File> fileList = new ArrayList<>();

    /**
     * 去除文件列表里图片的水印并替换
     *
     */
    public static void convertAllImages(List<File> fileList) {
        try {
            for (File file : fileList) {
                if (!file.getName().endsWith("png") && !file.getName().endsWith("jpg")) {
                    continue;
                }
                BufferedImage bi = ImageIO.read(file); //用ImageIO流读取像素块
                if (bi != null) {
                    removeWatermark(bi);
                    String formatName = file.getName().substring(file.getName().lastIndexOf(".") + 1);//生成的图片格式
                    ImageIO.write(bi, formatName, file);//用ImageIO流生成的处理图替换原图片
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从源目录获取图片处理后导出到目标目录
     *
     * @param dir     源目录
     * @param saveDir 目标目录
     */
    private static void convertAllImages(String dir, String saveDir) {
        File dirFile = new File(dir);
        File saveDirFile = new File(saveDir);
        dir = dirFile.getAbsolutePath();
        saveDir = saveDirFile.getAbsolutePath();
        loadImages(new File(dir));
        for (File file : fileList) {
            String filePath = file.getAbsolutePath();
            String dstPath = saveDir + filePath.substring(filePath.indexOf(dir) + dir.length());
            replace(file.getAbsolutePath(), dstPath);
        }
    }

    /**
     * 加载图片
     */
    private static void loadImages(File f) {
        if (f != null) {
            if (f.isDirectory()) {
                File[] fileArray = f.listFiles();
                if (fileArray != null) {
                    for (File file : fileArray) {
                        loadImages(file); //递归调用
                    }
                }
            } else {
                String name = f.getName();
                if (name.endsWith("png") || name.endsWith("jpg")) {
                    fileList.add(f);
                }
            }
        }
    }

    /**
     * 生成源图片的处理图
     *
     * @param srcFile 源图片路径
     * @param dstFile 目标图片路径
     */
    private static void replace(String srcFile, String dstFile) {
        try {
            URL http;
            if (srcFile.trim().startsWith("https")) {
                http = new URL(srcFile);
                HttpsURLConnection conn = (HttpsURLConnection) http.openConnection();
                conn.setRequestMethod("GET");
            } else if (srcFile.trim().startsWith("http")) {
                http = new URL(srcFile);
                HttpURLConnection conn = (HttpURLConnection) http.openConnection();
                conn.setRequestMethod("GET");
            } else {
                http = new File(srcFile).toURI().toURL();
            }
            BufferedImage bi = ImageIO.read(http.openStream());
            if (bi != null) {
                removeWatermark(bi);
                exportImage(bi, srcFile, dstFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 由ImageIO流生成源图片的处理图
     *
     * @param bi       ImageIO
     * @param fileName 源图片带后缀的文件名
     * @param dstFile  目标图片路径
     */
    private static void exportImage(BufferedImage bi, String fileName, String dstFile) {
        try {
            String type = fileName.substring(fileName.lastIndexOf(".") + 1);
            Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(type);
            ImageWriter writer = it.next();
            File f = new File(dstFile);
            ImageOutputStream ios = ImageIO.createImageOutputStream(f);
            writer.setOutput(ios);
            writer.write(bi);
            bi.flush();
            ios.flush();
            ios.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 去除水印
     */
    private static void removeWatermark(BufferedImage bi) {
        Color wColor = Color.blue;
//        Color hColor = new Color(197, 196, 191);
//        Color wColor = new Color(255, 0, 0);
        //白底水印
        for (int i = 0; i < bi.getWidth(); i++) {
            for (int j = 0; j < bi.getHeight(); j++) {
                int color = bi.getRGB(i, j);
                Color oriColor = new Color(color);
                int red = oriColor.getRed();
                int greed = oriColor.getGreen();
                int blue = oriColor.getBlue();
                if (red > 203 && greed > 76 && blue > 75) {
                    bi.setRGB(i, j, wColor.getRGB());
                }
//                if (red > 220 && greed > 180 && blue > 80) {
//                    bi.setRGB(i, j, wColor.getRGB());
//                }
//                if (red <= 240 && greed >= 200 && blue >= 150) {
//                    bi.setRGB(i, j, wColor.getRGB());
//                }
            }
        }
    }


    public static void main(String[] args){
//        File img = new File("D:/头像.png");
//        try(FileOutputStream os = new FileOutputStream(new File("D:/a.png"))){
//            markeWatermark(img,"测试",os);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        fileList.add(new File("D:/a.png"));
        convertAllImages(fileList);

    }

}